package com.example.service.impl;

import com.example.domian.Dept;
import com.example.domian.DeptEmp;
import com.example.domian.Emp;
import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.service.DeptService;
import com.example.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

//操作Dept的业务层接口实现类
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpService empService;

    //查询所有部门
    @Override
    public List<Dept> selectAll() {
        return deptMapper.selectAll();
    }

    //根据id查询部门
    @Override
    public Dept selectById(Integer id) {
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    //根据id删除部门
    @Override
    public void deleteById(Integer id) {
        deptMapper.deleteById(id);
    }

    //添加部门
    @Override
    public void add(String name) {
        LocalDateTime now = LocalDateTime.now();
        Dept dept = new Dept(null, name, now, now);
        deptMapper.add(dept);
    }

    //修改部门
    @Override
    public void update(Integer id, String name) {
        LocalDateTime now = LocalDateTime.now();
        Dept dept = new Dept(id, name, now, now);
        deptMapper.update(dept);
    }

    //根据id查询部门包含员工
    @Override
    public DeptEmp findByIdWithEmp(Integer id) {
        Dept dept = deptMapper.selectById(id);
        if (dept==null){
            return null;
        }
        List<Emp> emps = empService.findByDeptId(id);
        DeptEmp deptEmp = DeptEmp.builder()
                .id(dept.getId())
                .name(dept.getName())
                .createTime(dept.getCreateTime())
                .updateTime(dept.getUpdateTime())
                .emps(emps)
                .build();
        return deptEmp;
    }


}
